package com.itheima.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author :wujunjie
 * createTime :2022-12-26 17:11
 * description :
 */

@Order(-1)
//todo 打开拦截器
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {
    @Autowired
    private WhiteListProperties whiteList;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 添加放行路径
        String path = exchange.getRequest().getPath().toString();
        if (whiteList.getWhiteList().contains(path)) {
            return chain.filter(exchange);
        }
        //获取token
        MultiValueMap<String, String> headers = exchange.getRequest().getHeaders();
        String token = headers.getFirst("token");
        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("未发现有效token");
        }
        //token时间校验
        try {
            JWTValidator.of(token).validateDate(DateUtil.date());
        }catch (ValidateException v){
            throw new RuntimeException("token已过期");
        }
        //校验token
        boolean verify = JWTUtil.verify(token, "heimaLeadnews".getBytes());
        if (!verify) {
            return getVoidMono(exchange);
        }
        //解析token，取出信息
        JWT jwt = JWTUtil.parseToken(token);
        if (ObjectUtils.isEmpty(jwt)) {
            return getVoidMono(exchange);
        }
        Object id = jwt.getPayload("id");
        if (ObjectUtils.isEmpty(id)) {
            return getVoidMono(exchange);
        }
        //把token里面携带的信息放到请求头中
        ServerHttpRequest requestNew = exchange.getRequest().mutate().headers(httpHeaders -> httpHeaders.add("id", id.toString())).build();
        //重建请求头
        exchange.mutate().request(requestNew).build();
        return chain.filter(exchange);
    }

    private static Mono<Void> getVoidMono(ServerWebExchange exchange) {
        //修改请求响应状态
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }


}
